package org.cogaen.sound;

import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

import org.cogaen.core.Core;
import org.cogaen.resource.ResourceHandle;
import org.cogaen.resource.ResourceManager;

/**
 * @class SoundHandle
 * @author Florian Lettner
 *
 * @brief A sound handle that can be added to a resource manager.
 */
public class SoundHandle extends ResourceHandle{
	
	/** @brief The filename where the sound file is stored. */
	private String filename;
	private SoundEffect soundeffect;
	
	/**
	 * @brief Creates a new sound handle.
	 * 
	 * @param name The name of the handle.
	 * @param filename The filename of the handle.
	 */
	public SoundHandle(String name, String filename) {
		super(name);
		this.filename = filename;
	}
	
	/**
	 * @brief Provides the caller with the sampledata of the sound handle.
	 * 
	 * @throws RuntimeException
	 */
	@Override
	public Object getResource() {
		if (!isLoaded()) {
			throw new RuntimeException("resource not loaded");
		}
		return this.soundeffect;
	}

	/**
	 * @brief Checks if the sound handle is loaded.
	 * 
	 * @return true if the handle is loaded; otherwise false.
	 */
	@Override
	public boolean isLoaded() {
		return this.soundeffect != null;
	}

	/**
	 * @brief Loads the sound handle.
	 * 
	 * @core The engine's core.
	 */
	@Override
	public void load(Core core) {
		URL url = ResourceManager.getInstance(core).getUrl(this.filename);
		AudioInputStream audioStream = null;
		
		try {
			audioStream = AudioSystem.getAudioInputStream(url);
		} catch (UnsupportedAudioFileException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (IllegalArgumentException ex) {
			ex.printStackTrace();
		}
		
		soundeffect = new SoundEffect(audioStream);
	}

	/**
	 * @brief Unloads the sound handle.
	 */
	@Override
	public void unload() {
		this.soundeffect = null;
	}
}
